import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

interface StationVisit {
  stationId: string;
  stationName: string;
  timestamp: number;
  passengerCount: number;
}

interface DailyFlowData {
  date: string;
  totalPassengers: number;
  stations: Record<string, number>; // stationId -> passenger count
}

export const usePassengerFlowStore = defineStore(
  'passengerFlow',
  () => {
    // 存储站点访问记录
    const stationVisits = ref<StationVisit[]>([]);
    
    // 按日期分组的客流量数据
    const dailyFlowData = ref<DailyFlowData[]>([]);

    // 记录站点访问
    function recordStationVisit(stationId: string, stationName: string, passengerCount: number = 10) {
      const visit: StationVisit = {
        stationId,
        stationName,
        timestamp: Date.now(),
        passengerCount
      };
      
      stationVisits.value.push(visit);
      
      // 更新每日数据
      updateDailyData(visit);
    }

    // 更新每日数据
    function updateDailyData(visit: StationVisit) {
      const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD 格式
      
      // 查找今天的数据
      let todayData = dailyFlowData.value.find(data => data.date === today);
      
      if (!todayData) {
        // 如果今天的数据不存在，创建新记录
        todayData = {
          date: today,
          totalPassengers: 0,
          stations: {}
        };
        dailyFlowData.value.push(todayData);
      }
      
      // 更新总客流量
      todayData.totalPassengers += visit.passengerCount;
      
      // 更新站点客流量
      if (!todayData.stations[visit.stationId]) {
        todayData.stations[visit.stationId] = 0;
      }
      todayData.stations[visit.stationId] += visit.passengerCount;
    }

    // 获取最近N天的客流量数据
    function getRecentDaysFlow(days: number = 7) {
      // 按日期排序，最近的日期在前
      const sortedData = [...dailyFlowData.value].sort((a, b) => 
        new Date(b.date).getTime() - new Date(a.date).getTime()
      );
      
      return sortedData.slice(0, days);
    }

    // 获取总客流量
    const totalPassengers = computed(() => {
      return dailyFlowData.value.reduce((sum, data) => sum + data.totalPassengers, 0);
    });

    // 获取最受欢迎的站点（访问次数最多）
    const popularStations = computed(() => {
      const stationCounts: Record<string, { id: string, name: string, count: number }> = {};
      
      stationVisits.value.forEach(visit => {
        if (!stationCounts[visit.stationId]) {
          stationCounts[visit.stationId] = {
            id: visit.stationId,
            name: visit.stationName,
            count: 0
          };
        }
        stationCounts[visit.stationId].count += visit.passengerCount;
      });
      
      return Object.values(stationCounts).sort((a, b) => b.count - a.count);
    });

    // 获取每小时客流量分布
    const hourlyDistribution = computed(() => {
      const hourCounts = Array(24).fill(0);
      
      stationVisits.value.forEach(visit => {
        const hour = new Date(visit.timestamp).getHours();
        hourCounts[hour] += visit.passengerCount;
      });
      
      return hourCounts;
    });

    // 清除所有数据（用于测试）
    function clearAllData() {
      stationVisits.value = [];
      dailyFlowData.value = [];
    }

    return {
      stationVisits,
      dailyFlowData,
      recordStationVisit,
      getRecentDaysFlow,
      totalPassengers,
      popularStations,
      hourlyDistribution,
      clearAllData
    }
  },
  {
    persist: true // 持久化存储
  }
)
